﻿using HardcoreGame.Common.Systems;
using Microsoft.Xna.Framework;
using Microsoft.Xna.Framework.Graphics;
using System.Collections.Generic;
using System.Linq;
using Terraria;
using Terraria.Audio;
using Terraria.GameContent;
using Terraria.GameContent.UI.Elements;
using Terraria.GameInput;
using Terraria.ID;
using Terraria.Localization;
using Terraria.ModLoader;
using Terraria.UI;

namespace HardcoreGame.Content.Items.Accessories
{
    public class DesertTurtleShell : ModItem
    {
        public const int MAX_ABSORBED_DAMAGE = 200;
        public const int COOLDOWN_DURATION = 300;
        public const int ENCHANTMENT_DURATION = 600;
        public override void SetDefaults()
        {
            Item.width = 20;
            Item.height = 24;
            Item.value = 225000;
            Item.accessory = true;
            Item.rare = ItemRarityID.Pink;
        }
        public override void UpdateAccessory(Player player, bool hideVisual)
        {
            player.GetModPlayer<DesertTurtleShellPlayer>().hasTurtleShell = true;
        }
    }
    public class DesertTurtleShellPlayer : ModPlayer
    {
        public bool hasTurtleShell = false;
        public int absorbedDamage = 0;
        public int cooldownTimer = 0;
        public bool isWeaponEnchanted = false;
        public int enchantmentTimer = 0;
        public int enchantedDamage = 0;

        public override void ResetEffects()
        {
            hasTurtleShell = false;
        }

        public override void UpdateDead()
        {
            absorbedDamage = 0;
            cooldownTimer = 0;
            isWeaponEnchanted = false;
            enchantmentTimer = 0;
            enchantedDamage = 0;
        }

        public override void PostUpdate()
        {
            if (hasTurtleShell)
            {
                if (cooldownTimer > 0)
                {
                    cooldownTimer--;
                }
                if (isWeaponEnchanted)
                {
                    enchantmentTimer--;
                    if (enchantmentTimer <= 0)
                    {
                        isWeaponEnchanted = false;
                        enchantedDamage = 0;
                    }
                }
            }
        }

        public override void ModifyHitByNPC(NPC npc, ref Player.HurtModifiers modifiers)
        {
            if (hasTurtleShell && !isWeaponEnchanted && cooldownTimer <= 0)
            {
                int absorbed = (int)MathHelper.Min(npc.damage / 2, DesertTurtleShell.MAX_ABSORBED_DAMAGE - absorbedDamage);

                if (absorbed > 0)
                {
                    modifiers.FinalDamage -= absorbed;
                    absorbedDamage += absorbed;
                    for (int i = 0; i < absorbed / 5; i++)
                    {
                        Dust.NewDust(Player.position, Player.width, Player.height, DustID.Sand, 0f, 0f, 100, default, 1.2f);
                    }
                    SoundEngine.PlaySound(SoundID.Item28, Player.Center);
                }
            }
        }

        public override void ModifyHitByProjectile(Projectile proj, ref Player.HurtModifiers modifiers)
        {
            if (hasTurtleShell && !isWeaponEnchanted && cooldownTimer <= 0)
            {
                int absorbed = (int)MathHelper.Min(proj.damage / 2, DesertTurtleShell.MAX_ABSORBED_DAMAGE - absorbedDamage);

                if (absorbed > 0)
                {
                    modifiers.FinalDamage -= absorbed;
                    absorbedDamage += absorbed;
                    for (int i = 0; i < absorbed / 5; i++)
                    {
                        Dust.NewDust(Player.position, Player.width, Player.height, DustID.Sand, 0f, 0f, 100, default, 1.2f);
                    }
                    SoundEngine.PlaySound(SoundID.Item28, Player.Center);
                }
            }
        }

        public override void ModifyWeaponDamage(Item item, ref StatModifier damage)
        {
            if (hasTurtleShell && isWeaponEnchanted && Player.inventory[Player.selectedItem].damage > 0)
            {
                damage.Base += enchantedDamage;
                if (Main.rand.NextBool(3))
                {
                    Dust.NewDust(Player.position, Player.width, Player.height, DustID.Gold, 0f, 0f, 100, default, 1.2f);
                }
            }
        }

        public override void ProcessTriggers(TriggersSet triggersSet)
        {
            if (hasTurtleShell && KeybindSystem.DesertTurtleShell.JustPressed && absorbedDamage > 0 && cooldownTimer <= 0 && !isWeaponEnchanted)
            {
                isWeaponEnchanted = true;
                enchantmentTimer = DesertTurtleShell.ENCHANTMENT_DURATION;
                enchantedDamage = absorbedDamage;
                absorbedDamage = 0;
                cooldownTimer = DesertTurtleShell.COOLDOWN_DURATION;
                SoundEngine.PlaySound(SoundID.Item74, Player.Center);
                for (int i = 0; i < 30; i++)
                {
                    Dust.NewDust(Player.position, Player.width, Player.height, DustID.Sandstorm, 0f, 0f, 100, default, 1.5f);
                }
            }
        }
    }
    public class DesertTurtleShellUI : ModSystem
    {
        private UserInterface turtleShellInterface;
        private DesertTurtleShellBar turtleShellBar;

        public override void Load()
        {
            if (!Main.dedServ)
            {
                turtleShellBar = new DesertTurtleShellBar();
                turtleShellBar.Activate();
                turtleShellInterface = new UserInterface();
                turtleShellInterface.SetState(turtleShellBar);
            }
        }

        public override void UpdateUI(GameTime gameTime)
        {
            if (turtleShellInterface?.CurrentState != null)
            {
                turtleShellInterface.Update(gameTime);
            }
        }

        public override void ModifyInterfaceLayers(List<GameInterfaceLayer> layers)
        {
            int mouseTextIndex = layers.FindIndex(layer => layer.Name.Equals("Vanilla: Mouse Text"));
            if (mouseTextIndex != -1)
            {
                layers.Insert(mouseTextIndex, new LegacyGameInterfaceLayer(
                    "HardcoreGame: Turtle Shell Bar",
                    delegate
                    {
                        if (Main.LocalPlayer.GetModPlayer<DesertTurtleShellPlayer>().hasTurtleShell)
                        {
                            turtleShellInterface.Draw(Main.spriteBatch, new GameTime());
                        }
                        return true;
                    },
                    InterfaceScaleType.UI)
                );
            }
        }
    }
    public class DesertTurtleShellBar : UIState
    {
        private UIText text;
        private UIText enchantmentText;
        private Color gradientA = new(255, 200, 100);
        private Color gradientB = new(255, 100, 50);
        private Color borderColor = new(100, 60, 20);
        private Color backgroundColor = new(50, 30, 10, 200);
        private Color enchantmentColor = new(255, 215, 0);

        public override void OnInitialize()
        {
            text = new UIText("0/200", 0.8f)
            {
                HAlign = 0.5f,
                VAlign = 0.5f
            };
            Append(text);
            enchantmentText = new UIText("", 0.8f)
            {
                HAlign = 0.5f
            };
            enchantmentText.Top.Set(20f, 0f);
            enchantmentText.TextColor = enchantmentColor;
            Append(enchantmentText);
        }

        protected override void DrawSelf(SpriteBatch spriteBatch)
        {
            base.DrawSelf(spriteBatch);

            var modPlayer = Main.LocalPlayer.GetModPlayer<DesertTurtleShellPlayer>();
            Vector2 playerPosition = Main.LocalPlayer.Center;
            playerPosition.Y += Main.LocalPlayer.height / 2 + 20;
            Vector2 screenPosition = playerPosition - Main.screenPosition;
            Rectangle barRect = new((int)screenPosition.X - 60, (int)screenPosition.Y, 120, 24);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, barRect, backgroundColor);
            DrawBorder(spriteBatch, barRect, 2, borderColor);
            float quotient = (float)modPlayer.absorbedDamage / DesertTurtleShell.MAX_ABSORBED_DAMAGE;
            quotient = MathHelper.Clamp(quotient, 0f, 1f);
            int width = (int)(barRect.Width * quotient);
            if (width > 0)
            {
                Rectangle energyBar = new(barRect.X + 2, barRect.Y + 2, width - 4, barRect.Height - 4);
                for (int i = 0; i < energyBar.Width; i++)
                {
                    float progress = (float)i / energyBar.Width;
                    Color currentColor = Color.Lerp(gradientA, gradientB, progress);
                    spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle(energyBar.X + i, energyBar.Y, 1, energyBar.Height), currentColor);
                }
            }
            text.SetText($"{modPlayer.absorbedDamage}/{DesertTurtleShell.MAX_ABSORBED_DAMAGE}");
            text.Left.Set(barRect.X + barRect.Width / 2 - text.Width.Pixels / 2, 0f);
            text.Top.Set(barRect.Y + barRect.Height / 2 - text.Height.Pixels / 2, 0f);
            if (modPlayer.isWeaponEnchanted)
            {
                for (int i = 0; i < 2; i++)
                {
                    Dust dust = Dust.NewDustPerfect(
                        new Vector2(barRect.X + Main.rand.Next(barRect.Width), barRect.Y - 10),
                        DustID.Gold,
                        new Vector2(0, -0.5f),
                        100,
                        default,
                        1.2f
                    );
                    dust.noGravity = true;
                }
            }
            else
            {
                enchantmentText.SetText("");
            }
            if (barRect.Contains(Main.mouseX, Main.mouseY))
            {
                Main.hoverItemName = Language.GetTextValue("Mods.HardcoreGame.UI.2") + modPlayer.absorbedDamage + "/" + DesertTurtleShell.MAX_ABSORBED_DAMAGE;

                if (modPlayer.cooldownTimer > 0)
                {
                    Main.hoverItemName += "\n" + Language.GetTextValue("Mods.HardcoreGame.UI.3") + (modPlayer.cooldownTimer / 60) + Language.GetTextValue("Mods.HardcoreGame.UI.4");
                }
                else if (modPlayer.absorbedDamage > 0)
                {
                    Main.hoverItemName += "\n" + Language.GetTextValue("Mods.HardcoreGame.UI.5") + KeybindSystem.DesertTurtleShell.GetAssignedKeys().FirstOrDefault() + Language.GetTextValue("Mods.HardcoreGame.UI.6");
                }
            }
        }
        private static void DrawBorder(SpriteBatch spriteBatch, Rectangle rect, int thickness, Color color)
        {
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle(rect.X, rect.Y, rect.Width, thickness), color);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle(rect.X, rect.Y + rect.Height - thickness, rect.Width, thickness), color);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle(rect.X, rect.Y, thickness, rect.Height), color);
            spriteBatch.Draw(TextureAssets.MagicPixel.Value, new Rectangle(rect.X + rect.Width - thickness, rect.Y, thickness, rect.Height), color);
        }
    }
}